<script setup lang="ts">
import { storeToRefs } from 'pinia'
// #ifdef APP-PLUS
import { ref } from 'vue'
import { addMe, editMe, getMe } from '@/api/me'
import { useUserStore } from '@/store'
import { useTokenStore } from '@/store/token'
// 页面配置
definePage({
  style: {
    navigationBarTitleText: '我的',
  },
})

const userStore = useUserStore()
const tokenStore = useTokenStore()
const { userInfo } = storeToRefs(userStore)
const popShow = ref(false)
onShow(async () => {
  const userId = userStore.userInfo.userId
  console.log('userId', userId)
  const res = await getMe(userId)
  console.log('userInfo', userInfo.value, res)
  // 检查数据是否为空
  if (res.length === 0) {
    popShow.value = true
  }
  else {
    userData.value.department = res[0].department || ''
    userData.value.description = res[0].introduct || ''
    userData.value.avatar = res[0].avatar || '/static/images/default-avatar.png'
  }
})
// 弹窗中使用的临时数据
const popupDepartment = ref('')
const popupDescription = ref('')

// 弹窗中的科室选择确认处理
function handlePopupDepartmentConfirm({ value }) {
  popupDepartment.value = value
}

// 弹窗确定按钮处理
async function handlePopupConfirm() {
  // 验证输入
  if (!popupDepartment.value) {
    uni.showToast({ title: '请选择科室', icon: 'none' })
    return
  }

  // 调用handleAdd并传入编辑的内容
  const userId = userStore.userInfo.userId
  const res
    = await addMe({
      userId,
      department: popupDepartment.value,
      introduct: popupDescription.value,
    })

  console.log('addMe popup', res, userId, popupDepartment.value, popupDescription.value)

  // 关闭弹窗
  popShow.value = false

  // 如果添加成功，更新用户数据
  if (res.code === 200) {
    userData.value.department = popupDepartment.value
    userData.value.description = popupDescription.value

    // 显示成功提示
    uni.showToast({
      title: '信息添加成功',
      icon: 'success',
      duration: 2000,
    })
  }
}

// 弹窗关闭处理
function handleClose() {
  popShow.value = false
  // 重置弹窗数据
  popupDepartment.value = ''
  popupDescription.value = ''
}
// 从 userInfo 中获取
const userData = ref({
  avatar: userInfo.value.avatar || '/static/images/default-avatar.png',
  name: userInfo.value.username || '未设置',
  department: userInfo.value.department || '',
  description: userInfo.value.introduct || '',
})

// 部门选择相关状态
const columns = ref(['内科', '外科', '儿科', '妇产科', '眼科', '口腔科', '皮肤科'])
const showDepartmentPicker = ref(false)
const departmentValue = ref('')
// 处理部门选择器显示
function handleDepartmentPicker() {
  // 显示选择器
  showDepartmentPicker.value = true
  // 初始化选择值
  departmentValue.value = userData.value.department
}
// 描述编辑相关状态
const showDescriptionEditor = ref(false)
const editingDescription = ref('')
function handleDescriptionEdit() {
  // 显示编辑框
  showDescriptionEditor.value = true
  // 初始化编辑内容
  editingDescription.value = userData.value.description
}
// 处理部门选择确认
function handleDepartmentConfirm({ value }) {
  departmentValue.value = value
  // 隐藏选择器
  showDepartmentPicker.value = false
  // 更新用户数据
  userData.value.department = value
  // 触发保存函数
  saveUserData()
}

// 处理描述编辑保存
function handleDescriptionSave() {
  // 更新用户数据
  userData.value.description = editingDescription.value
  // 触发保存函数
  saveUserData()
  // 隐藏编辑框
  showDescriptionEditor.value = false
}

// 保存用户数据
async function saveUserData() {
  console.log('保存用户数据:', userData.value)
  const userId = userStore.userInfo.userId
  const res = await editMe({
    userId,
    department: userData.value.department,
    introduct: userData.value.description,
  })
  console.log('editMe', res)
  if (res === 1) {
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 2000,
    })
  }
}

// 退出登录
function handleLogout() {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清空用户信息
        useTokenStore().logout()
        // 执行退出登录逻辑
        uni.showToast({
          title: '退出登录成功',
          icon: 'success',
          duration: 2000,
        })
      }
    },
  })
}

// 跳转到接诊设置页面
function navigateToAdmitSettings() {
  uni.navigateTo({
    url: '/pages/me/more/admit',
  })
}

// 跳转到个人资料编辑页面
function navigateToProfileEdit() {
  // 实际项目中应该有个人资料编辑页面
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
    duration: 2000,
  })
}

// 跳转到通知设置页面
function navigateToNotificationSettings() {
  // 实际项目中应该有通知设置页面
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
    duration: 2000,
  })
}

// 跳转到帮助与反馈页面
function navigateToHelpFeedback() {
  // 实际项目中应该有帮助与反馈页面
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
    duration: 2000,
  })
}

// #endif
</script>

<template>
  <!-- #ifdef APP-PLUS -->
  <view class="profile-container min-h-screen bg-gray-50">
    <!-- 个人信息区域 -->
    <view class="bg-white p-6">
      <view class="mb-6 flex items-center">
        <!-- 头像 -->
        <view class="relative">
          <image
            :src="userData.avatar" class="h-20 w-20 border-2 border-white rounded-full shadow-md"
            mode="aspectFill"
          />
          <!-- <view class="absolute bottom-0 right-0 w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">
            <text class="text-white text-xs">编辑</text>
          </view> -->
        </view>

        <!-- 用户基本信息 -->
        <view class="ml-4 flex-1">
          <view class="flex items-center justify-between">
            <text class="text-lg font-bold">{{ userData.name }}</text>
            <!-- <text class="text-blue-500 text-sm">在线</text> -->
          </view>
          <!-- 部门选择器 -->
          <wd-picker
            v-if="showDepartmentPicker" v-model="departmentValue" :columns="columns" label="选择科室"
            @confirm="handleDepartmentConfirm" @cancel="showDepartmentPicker = false"
          />
          <text v-else class="mt-1 block text-gray-500" @click="handleDepartmentPicker">
            {{ userData.department }} <text class="ml-1 text-xs text-blue-400">点击修改</text>
          </text>
        </view>
      </view>

      <!-- 个人描述 -->
      <view class="rounded-lg bg-gray-50 p-3">
        <view v-if="!showDescriptionEditor" @click="handleDescriptionEdit">
          <text class="line-clamp-2 text-sm text-gray-600">{{ userData.description }}</text>
          <text class="ml-1 text-xs text-blue-400">点击修改</text>
        </view>
        <view v-else class="rounded bg-white p-2">
          <textarea v-model="editingDescription" class="h-20 w-full text-sm" placeholder="请输入个人描述" />
          <view class="mt-2 flex justify-end">
            <button type="default" size="mini" class="mr-2" @click="showDescriptionEditor = false">
              取消
            </button>
            <button type="primary" size="mini" @click="handleDescriptionSave">
              保存
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 设置列表区域 -->
    <view class="mt-4 bg-white">
      <!-- 设置项分组标题 -->
      <view class="border-b border-gray-100 px-4 py-2">
        <text class="text-sm text-gray-500">功能设置</text>
      </view>

      <!-- 设置项列表 -->
      <view class="divide-y divide-gray-100">
        <!-- 接诊设置 -->
        <view class="flex items-center justify-between bg-white p-4" @click="navigateToAdmitSettings">
          <view class="flex items-center">
            <!-- <view class="w-8 h-8 rounded-full bg-green-100 flex items-center justify-center">
              <text class="text-green-500 text-sm">接诊</text>
            </view> -->
            <text class="ml-3">接诊设置</text>
          </view>
          <view class="flex items-center">
            <text class="mr-2 text-sm text-gray-400">管理接诊时间和号段</text>
            <image src="/static/images/arrow-right.png" class="h-4 w-4 text-gray-400" mode="aspectFill" />
          </view>
        </view>

        <!-- 其他设置项 -->
        <!-- <view class="flex items-center justify-between p-4 bg-white" @click="navigateToProfileEdit">
          <view class="flex items-center">
            <text class="ml-3">个人资料</text>
          </view>
          <view class="flex items-center">
            <image src="/static/images/arrow-right.png" class="w-4 h-4 text-gray-400" mode="aspectFill" />
          </view>
        </view>

        <view class="flex items-center justify-between p-4 bg-white" @click="navigateToNotificationSettings">
          <view class="flex items-center">
            <text class="ml-3">通知设置</text>
          </view>
          <view class="flex items-center">
            <image src="/static/images/arrow-right.png" class="w-4 h-4 text-gray-400" mode="aspectFill" />
          </view>
        </view> -->

        <!-- <view class="flex items-center justify-between p-4 bg-white" @click="navigateToHelpFeedback">
          <view class="flex items-center">
            <view class="w-8 h-8 rounded-full bg-purple-100 flex items-center justify-center">
              <text class="text-purple-500 text-sm">帮助</text>
            </view>
            <text class="ml-3">帮助与反馈</text>
          </view>
          <view class="flex items-center">
            <image src="/static/images/arrow-right.png" class="w-4 h-4 text-gray-400" mode="aspectFill" />
          </view>
        </view> -->
      </view>
    </view>

    <!-- 底部退出登录按钮 -->
    <view v-if="tokenStore.hasLogin" class="p-6">
      <button type="warn" class="w-full" @click="handleLogout">
        退出登录
      </button>
    </view>
    <!-- 科室和介绍编辑弹窗 -->
    <wd-popup v-model="popShow" custom-class="rounded-32rpx w-80%" @close="handleClose">
      <view class="p-4">
        <text class="custom-txt mb-4 block text-lg font-bold">完善个人信息</text>

        <!-- 科室选择 -->
        <view class="mb-4">
          <text class="mb-2 block text-sm text-gray-600">选择科室</text>
          <wd-picker v-model="popupDepartment" :columns="columns" @confirm="handlePopupDepartmentConfirm" />
        </view>

        <!-- 介绍编辑 -->
        <view class="mb-6">
          <text class="mb-2 block text-sm text-gray-600">个人介绍</text>
          <textarea
            v-model="popupDescription" class="h-32 w-full border border-gray-200 rounded bg-gray-50 p-3 text-sm"
            placeholder="请输入个人介绍信息"
          />
        </view>

        <!-- 按钮组 -->
        <view class="flex space-x-4">
          <button type="default" class="flex-1" @click="handleClose">
            取消
          </button>
          <button type="primary" class="flex-1" @click="handlePopupConfirm">
            确定
          </button>
        </view>
      </view>
    </wd-popup>
  </view>
  <!-- #endif -->
</template>

<style scoped>
/* 使用UNOCSS原子化类名，此处仅保留必要的自定义样式 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
